package com.ohuang.ohrouter;

import android.content.Context;
import android.content.Intent;

public class OhRouter {
    private static volatile OhRouter ohRouter;
    private RouterHelper routerHelper;
    private boolean isInit = false;
    private Context context;

    private OhRouter() {
        routerHelper = new RouterHelper();
    }

    public static OhRouter get() {
        if (ohRouter == null) {
            synchronized (OhRouter.class) {
                if (ohRouter == null) {
                    ohRouter = new OhRouter();
                }
            }
        }
        return ohRouter;
    }


    public Object getObjetForPath(String path) {
        Class<?> c = getClassForPath(path);
        Object o;
        try {
            o = c.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("can not create " + c.getName() + " Path" + path);
        }
        return o;
    }

    public void startActivity(Context context, String path) {
        context.startActivity(getIntent(context, path));
    }

    public Intent getIntent(Context c, String path) {
        return new Intent(c, getClassForPath(path));
    }

    public Class<?> getClassForPath(String path) {

        Class<?> clzz = routerHelper.getClassForPath(path);
        if (clzz == null) {
            throw new RuntimeException("no find class for path" + path);
        }
        return clzz;
    }

    public String getClassName(String path) {
        return routerHelper.getClassForPath(path).getName();
    }

    public synchronized void init(Context context) {
        this.context=context;
        if (!isInit) {
            isInit = true;
            RouterLoader routerLoader = new RouterLoader(routerHelper);
            routerLoader.init(context);
        }
    }

    public void load(String key){
       routerHelper.loadRouterMap(key);
    }

}
